package com.wstuo.common.tools.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.tools.dao.IUserReturnVisitDAO;
import com.wstuo.common.tools.dto.UserReturnVisitDTO;
import com.wstuo.common.tools.dto.UserReturnVisitDetailDTO;
import com.wstuo.common.tools.dto.UserReturnVisitGridDTO;
import com.wstuo.common.tools.dto.UserReturnVisitQueryDTO;
import com.wstuo.common.tools.entity.UserReturnVisit;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.TimeUtils;

/**
 * 用户回访Service class
 * 
 * @author WSTUO
 * 
 */
public class UserReturnVisitService implements IUserReturnVisitService {
	private final static Logger LOGGER = Logger.getLogger(UserReturnVisitService.class);
	@Autowired
	private IUserReturnVisitDAO userReturnVisitDAO;
	@Autowired
	private IUserDAO userDAO;

	/**
	 * 保存用户回访
	 * 
	 * @param returnVisitDTO
	 */
	@Transactional
	public void saveUserReturnVisit(UserReturnVisitDTO returnVisitDTO) {
		UserReturnVisit entity = new UserReturnVisit();
		UserReturnVisitDTO.dto2entity(returnVisitDTO, entity);
		entity.setReturnVisitSubmitTime(new Date());
		userReturnVisitDAO.save(entity);
		returnVisitDTO.setVisitId(entity.getVisitId());
	}

	/**
	 * 编辑用户回访
	 * 
	 * @param returnVisitDTO
	 */
	@Transactional
	public void editUserReturnVisit(UserReturnVisitDTO returnVisitDTO) {
		UserReturnVisit entity = userReturnVisitDAO.findById(returnVisitDTO
				.getVisitId());
		UserReturnVisitDTO.dto2entity(returnVisitDTO, entity);
		userReturnVisitDAO.merge(entity);
	}

	/**
	 * 用户回访回复
	 * 
	 * @param returnVisitDTO
	 */
	@Transactional
	public boolean replyUserReturnVisit(UserReturnVisitDTO returnVisitDTO) {
		boolean blo=false;
		UserReturnVisit entity = userReturnVisitDAO.findById(returnVisitDTO.getVisitId());
		if (entity.getState().toString().equals("1")) {
			blo= false;
		} else {
			entity.setReturnVisitTime(new Date());
			entity.setSatisfaction(returnVisitDTO.getSatisfaction());
			entity.setState(1L);
			entity.setReturnVisitDetail(returnVisitDTO.getReturnVisitDetail());
			userReturnVisitDAO.merge(entity);
			blo= true;
		}
		return blo;
	}

	/**
	 * 删除用户回访
	 * 
	 * @param ids
	 */
	@Transactional
	public void deleteUserReturnVisit(final Long[] ids) {
		userReturnVisitDAO.deleteByIds(ids);
	}

	/**
	 * 分页查询用户回访记录
	 * @param queryDTO
	 * @param sidx
	 * @param sord
	 * @return PageDTO
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findPagerReturnVisit(UserReturnVisitQueryDTO queryDTO,String sidx, String sord) {
		PageDTO p = userReturnVisitDAO.findPagerUserReturnVisit(queryDTO, sidx,sord);
		List<UserReturnVisit> entities = (List<UserReturnVisit>) p.getData();
		List<UserReturnVisitGridDTO> dtos = new ArrayList<UserReturnVisitGridDTO>(entities.size());
		for (UserReturnVisit entity : entities) {
			UserReturnVisitGridDTO adto = new UserReturnVisitGridDTO();
			UserReturnVisitGridDTO.entity2dto(entity, adto);
			dtos.add(adto);
		}
		p.setData(dtos);

		return p;
	}

	/**
	 * 根据ID获取用户回访详细记录
	 * 
	 * @param id
	 * @return UserReturnVisitDetailDTO
	 */
	@Transactional
	public UserReturnVisitDetailDTO findUserReturnVisitById(final Long id) {
		UserReturnVisitDetailDTO dto = new UserReturnVisitDetailDTO();
		UserReturnVisit entity = userReturnVisitDAO.findById(id);
		UserReturnVisitDetailDTO.entity2dto(entity, dto);
		if (entity.getReturnVisitTechnicianName() != null) {
			User us = userDAO.findUniqueBy("loginName",entity.getReturnVisitTechnicianName());
			if (us != null) {
				dto.setReturnVisitTechnicianName(us.getFullName());
			}
		}
		if (entity.getReturnVisitUser() != null) {
			User us2 = userDAO.findUniqueBy("loginName",entity.getReturnVisitUser());
			if (us2 != null) {
				dto.setReturnVisitUser(us2.getFullName());
			}
		}
		if (entity.getReturnVisitSubmitUser() != null) {
			User us3 = userDAO.findUniqueBy("loginName",entity.getReturnVisitSubmitUser());
			if (us3 != null) {
				dto.setReturnVisitSubmitUser(us3.getFullName());
			}
		}

		return dto;
	}

	/**
	 * 导出用户记录
	 * 
	 * @param queryDTO
	 * @param sidx
	 * @param sord
	 * @return InputStream
	 */
	@SuppressWarnings("unchecked")
    @Transactional
	public InputStream exportReturnVisit(UserReturnVisitQueryDTO queryDTO,
			String sidx, String sord) {

		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		List<String[]> data = new ArrayList<String[]>();
		LanguageContent lc = LanguageContent.getInstance();
		data.add(new String[] { lc.getContent("common.id"),
				lc.getContent("label.returnVisit.satisfaction"),
				lc.getContent("lable.ReturnVisitDetail"),
				lc.getContent("label.returnVisit.state"),
				lc.getContent("label.returnVisit.sendTime"),
				lc.getContent("label.returnVisit.replyTime"),
				lc.getContent("label.returnVisit.object"),
				lc.getContent("label.operator") });

		queryDTO.setLimit(CSVWriter.EXPORT_SIZE);
		PageDTO p = userReturnVisitDAO.findPagerUserReturnVisit(queryDTO,sidx,sord);
		if (p != null && p.getData() != null && p.getData().size() > 0) {
			List<UserReturnVisit> entities = p.getData();
			for (UserReturnVisit item : entities) {
				String visitState = "";
				String visitSatisfaction = "";
				String returnVisitDetail = "";
				if (item.getState().toString().equals("0")){
					visitState = lc.getContent("label.returnVisit.waitReply");
				} else {
					visitState = lc.getContent("label.returnVisit.alreadyReply");
				}
				visitSatisfaction=satisfaction2Chinese(item.getSatisfaction());
				if (item.getReturnVisitDetail() != null) {
					returnVisitDetail = item.getReturnVisitDetail().replaceAll(
							"<br><hr>", "/");
				}
				data.add(new String[] { item.getVisitId().toString(),
						visitSatisfaction, returnVisitDetail, visitState,
						TimeUtils.format(item.getReturnVisitSubmitTime(),TimeUtils.DATETIME_PATTERN),
						TimeUtils.format(item.getReturnVisitTime(),TimeUtils.DATETIME_PATTERN),
						item.getReturnVisitUser(),
						item.getReturnVisitSubmitUser() });
			}
		}

		csvw.writeAll(data);
		byte[] bs = null;
		try {
			bs = sw.getBuffer().toString().getBytes("GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		ByteArrayInputStream stream = null;
		if(bs!=null){
			stream = new ByteArrayInputStream(bs);
		}
		try {
        	if(csvw!=null){
        		csvw.flush();
    			csvw.close();
        	}
			if(sw!=null){
				sw.flush();
				sw.close();
			}
		} catch (IOException e) {
			LOGGER.error(e);
		}
		return stream;
	}
	
	private String satisfaction2Chinese(Long satisfaction){
		String visitSatisfaction = "";
		LanguageContent lc = LanguageContent.getInstance();
		if (satisfaction.toString().equals("5")) {
			visitSatisfaction = lc.getContent("label.returnVisit.verysatisfied");
		}
		if (satisfaction.toString().equals("4")) {
			visitSatisfaction = lc.getContent("label.returnVisit.satisfied");
		}
		if (satisfaction.toString().equals("3")) {
			visitSatisfaction = lc.getContent("label.returnVisit.general");
		}
		if (satisfaction.toString().equals("2")) {
			visitSatisfaction = lc.getContent("label.returnVisit.dissatisfied");
		}
		if (satisfaction.toString().equals("1")) {
			visitSatisfaction = lc.getContent("label.returnVisit.verydissatisfied");
		}
		return visitSatisfaction;
	}
	

}
